import { Message } from "@/types";
import { IconArrowUp, IconArrowBackUp, IconX } from "@tabler/icons-react";
import { FC, KeyboardEvent, useEffect, useRef, useState } from "react";

interface Props {
  onSend: (message: Message) => void;
  onRevert: () => void;
  isButtonDisabled: boolean;
  content: string;
  setContent: (content:string) => void
  loading: boolean;
}

export const ChatInput: FC<Props> = ({ onSend, onRevert, isButtonDisabled, content, setContent, loading}) => {
  // const [content, setContent] = useState<string>();

  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const value = e.target.value;
    if (value.length > 1000) {
      alert("Message limit is 1000 characters");
      return;
    }
    setContent(value);
  };

  const handleSend = () => {
    if (!content) {
      alert("Please enter a message");
      return;
    }
    onSend({ role: "user", content });
    setContent("");
  };

  const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey && !isButtonDisabled) {
      e.preventDefault();
      handleSend();
    }
  };

  useEffect(() => {
    if (textareaRef && textareaRef.current) {
      textareaRef.current.style.height = "inherit";
      textareaRef.current.style.height = `${textareaRef.current?.scrollHeight}px`;
    }
  }, [content]);

  return (
    <div className="relative">
      <textarea
        ref={textareaRef}
        className="min-h-[44px] rounded-lg pl-4 pr-20 py-2 w-full focus:outline-none focus:ring-1 focus:ring-neutral-300 border-2 border-neutral-200"
        style={{ resize: "none" }}
        placeholder="Type a message..."
        value={content}
        rows={1}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />
      {content ? (
      <button onClick={() => setContent("")}>
        <IconX className="absolute right-12 bottom-3 h-8 w-8 rounded-full p-1 bg-blue-500 hover:cursor-pointer hover:opacity-80 text-white" />
      </button>
      ) : (
      <button onClick={() => onRevert()} disabled={loading}> 
        <IconArrowBackUp className={`absolute right-12 bottom-3 h-8 w-8 rounded-full p-1 ${loading ? 'bg-gray-500' : 'bg-blue-500 hover:cursor-pointer hover:opacity-80'} text-white`} />
      </button>
      )}
      <button onClick={() => handleSend()} disabled={isButtonDisabled}>
        <IconArrowUp className={`absolute right-2 bottom-3 h-8 w-8 rounded-full p-1 ${isButtonDisabled ? 'bg-gray-500' : 'bg-blue-500 hover:cursor-pointer hover:opacity-80'} text-white`} />
      </button>
    </div>
  );
};
